package com.chat.common.common.event.Listener;

import com.chat.common.common.event.UserApplyEvent;
import com.chat.common.user.dao.UserApplyDao;
import com.chat.common.user.domain.entity.User;
import com.chat.common.user.domain.entity.UserApply;
import com.chat.common.user.domain.vo.resp.ws.WSFriendApply;
import com.chat.common.user.service.impl.PushService;
import com.chat.common.websocket.domain.enums.WSBaseResp;
import com.chat.common.websocket.service.adapter.WebSocketAdapter;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

@Component
public class UserApplyListener{
    @Resource
    private UserApplyDao userApplyDao;
    @Resource
    private PushService pushService;

    @Async
    @TransactionalEventListener(classes = UserApplyEvent.class, fallbackExecution = true)
    public void handleEvent(UserApplyEvent event){
        UserApply userApply = event.getUserApply();
        // 接收人的未读消息数量
        Integer unReadCount = userApplyDao.getUnReadCount(userApply.getTargetId());
        //接受人的 id 以及 未读消息数
        WSBaseResp<WSFriendApply> wsFriendApplyWSBaseResp = WebSocketAdapter.buildApplySend(new WSFriendApply(userApply.getUid(), unReadCount));
        //消息推送给到前端
        pushService.sendPushMsg(wsFriendApplyWSBaseResp, userApply.getTargetId());
    }
}
